<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'app_id' => '2021002110644323',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoJx8ryqOcJWkrAQ2HQUGEsTBGqXQnwX/br6535ruOYcErCfbbZwUnj9XLn3FFejCobtArW12Ix/jamzx3PYCASecFYdOJGbL8NPyVhjBfDJYVpQFw2GqC+xNbvdKsZew1TC8Zu3SBoaxeUSZy/jr742NCs4DJfvuUGtOCQmEdKE94vPru10ItZRRJmM6A+NXptDDRi7c2eDmSOJ469IU8ClE3tb4ZVgELRp0VHu9DUFXJbltCDhHsZPyBRRzIsra2Yca99f24D6melA6SB+Ov1oBuB4PODMS3SGTLL/zf0Eca7SPFWtF5jPzmhHm5WmgxsxaYIWUuYQMYmLRHkyNqQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi5Jf91G5rTqvzFmC4ixG6W0TMnY7Il23zrAHQk0D6klIrnlxWRu8l8EZk7RyBAmLsgz/wRyEHV+fpvq5GQ15nstKZqdyplGrqPzewX2GsGTn9Dof981p6JN2iomHs5B1dDD3KoQ3zbS/RkHjKbdqc4n6efss1BDLJu4ewN7W29K5ZsVSLbRlQWENZY2kXN/11kYL8BgpmL5b0wKVfnnpLrpXAfEl6/cC8oLnnn7mJ0ubgTynJF7yNGXx2O/ZDqagEChLcXsFh5FFKpuxmF2ElCwIhOZsSx79wEFd7Xzf+XhnzArLMRzZW4SGUyDBSWDP/1qxJykO0+zoVqDGrdnTRwIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAi5Jf91G5rTqvzFmC4ixG6W0TMnY7Il23zrAHQk0D6klIrnlxWRu8l8EZk7RyBAmLsgz/wRyEHV+fpvq5GQ15nstKZqdyplGrqPzewX2GsGTn9Dof981p6JN2iomHs5B1dDD3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rPDttbeeqIlhi0FyQrGCyR56kCgYAz252in3oMhS3gX5FBpOWOe/uql2iE/yR6EYpCA7w+3jHZiX2muS0l5Y8IjkIxYrbswEBjOaE6pCHwVXnS04HEdmAPwYwY5MK5UxBcbyoQuYzvQeARw4wbfxEBIcZSs8ERyykIbXO4rJA1Az/rkolgxcknjgPmV4tRVIi7nw6vQQKBgD0OwjHVZL61vrsryxgqMmgT3o5MezJUdgi6jhKxbVIw/JxlmxsDBEkWiDTzRZgnqWfutm0e2HUcTa5886mh7Zb49hVb6TxXIzaEEh3/JoKWbt4eZTauLGyqsfg4RwmZ+FVTzpRWLyw+L1T9eltQXwrnGN9jXAi+oj0QVfNRd6CT'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {

    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = $this->config['app_id'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://dui.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $back_order_id = $getInfo['trade_no']; // 订单号
                $result = $this->alltypespay($num,$back_order_id);
                if($result == true){
                    return 'success';
                }else{
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}